<?php
namespace app\user\controller;
use app\user\model\WeixinPay;
use app\user\model\Zfb;
use think\Db;
use think\facade\Request;
class Shop extends Common{
    protected $uid;
    public function initialize()
    {
        parent::initialize();
        $this->uid=session('user.id');
    }


    public function buycar(){
        if(empty($_SESSION['think']['user']['id'])){
            return array('code'=>0,'msg'=>'请登录后操作'); //商品已在购物车内
        }
        $shop_id=input('shopid');
        $info['shop_id']=$shop_id;
        $info['userid']=$_SESSION['think']['user']['id'];
        $info['time']=time();
        //判断商品是否存在购物车内
        $userinfo=db('shop_car')->where('shop_id='.$shop_id)->where('userid='.$_SESSION['think']['user']['id'])->find();
        if(!empty($userinfo['id'])){
            return array('code'=>0,'msg'=>'已经加入过购物车'); //商品已在购物车内
        }
        if(db('shop_car')->insert($info)!==false){
            return array('code'=>1,'msg'=>'成功加入购物车'); //商品已在购物车内
        }else{
            return array('code'=>0,'msg'=>'加入购物车失败'); //商品已在购物车内
        }



    }

    public function shopping_cart(){
        $shop_cart=db('shop_car')
            ->alias('s')
            ->join('__SHOP__ sp','s.shop_id=sp.id','left')
            ->field('s.*,sp.thumb,sp.title,sp.jiage')
            ->where('s.userid',$this->uid)
            ->select();
        $this->assign('shop_cart',$shop_cart);
        return view();
    }
    public function listbuy(){
        $key=$_SESSION['think']['user']['id'];


        $lists=db('shop_car')->alias('u')
            ->join(config('database.prefix').'shop ul','u.shop_id = ul.id','left')
            ->field('ul.id as bid,u.*,ul.title,ul.thumb,ul.jiage,ul.kucun')
            ->where('u.userid','=',$key)
            ->order('u.id desc')->select();

        $this->assign('lists',$lists);
        return view();


    }
    public function dellshop(){
        $id=input('id');
        //判断是不是自己的产品
        $dingdan= db('shop_car')->where('id='.$id)->find();
        if($dingdan['userid']==$_SESSION['think']['user']['id']){

            db('shop_car')->where('id='.$id)->delete();
            return 1;

        }else{

            return '2';

        }





    }
    public function jisuan(){
        $id=input('id');
        $num=input('num');


        $dingdan= db('shop')->where('id='.$id)->find();
        $dingdan=$dingdan['jiage'];
        if($num<=1){

            $num=1;
        }
        $jiage=$dingdan*$num;
        return $jiage;







    }

    public function buy(){
        $id=input('id');
        $num=input('num');
        if(empty($id)){
            return '没选择产品';
        }
        $userid=$_SESSION['think']['user']['id'];
        //获取产品价格
        $cp=db('shop')->where('id='.$id)->find();
        //获取用户信息
        $user=db('users')->where('id='.$userid)->find();
        //检查库存是否充足
        if(empty($num)){
            $num=1;
        }
        if($cp['kucun']<$num){
            return '库存不足';
            //exit;
        }
        //看看订单是否已经生成
        $dans = db('shop_dingdan')->where('userid='.$userid)->where('shop_id='.$id)->where('num='.$num)->where('pay_ok=0')->find();
        if(empty($dans['id'])){
            //生成订单
            $yCode = array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J');
            $orderSn = $yCode[intval(date('Y')) - 2011] . strtoupper(dechex(date('m'))) . date('d') . substr(time(), -5) . substr(microtime(), 2, 5) . sprintf('%02d', rand(0, 99));//订单号
            $dan['shop_id']=$id;
            $dan['userid']=$userid;
            $dan['danhao']=$orderSn;
            $dan['pay_ok']=0;
            $dan['is_ok']=1;
            $dan['num']=$num;
            $dan['time']=time();
            $dingdan=$cp['jiage'];
            if($num<=1){
                $num=1;
            }
            $jiage=$cp['jiage']*$num;
            $dan['xiaofei']=$jiage;
            $buy_next=db('shop_dingdan')->insertGetId($dan); // 添加订单
            //	 return $dingdan;
            $dan['zongjia']=$jiage;
        }else{
            $dan=db('shop_dingdan')->where('id='.$dans['id'])->find();
            if($num<=1){
                $num=1;
            }
            $dan['zongjia']= $cp['jiage']*$dan['num'];
            $buy_next=$dans['id'];
        }
        //获取允许支付类型
        $payopen=db('money_config')->where('open=1')->select();
        array_push($payopen, [
            'pic'=>'/static/mobile/images/wechat.png',
            'name'=>'微信',
            'id'=>'wechat',
        ]);
        array_push($payopen, [
            'pic'=>'/static/mobile/images/zfb.png',
            'name'=>'支付宝',
            'id'=>'zfb',
        ]);

        $this->assign('buyid',$buy_next);//输出订单ID
        $this->assign('ding_info',$dan);//输出订单信息

        $this->assign('pay',$payopen);
        $this->assign('user',$user);
        //输出当前用户信息以及是否允许信息



        return view();


    }

    public function buyok(){


        $id=input('dingid');

        //根据订单获取产品价格
        $type=input('paytype');
        $shopid=db('shop_dingdan')->where('id='.$id)->find();



        $num=$shopid['num'];
        $userid=$_SESSION['think']['user']['id'];

        //判断是否已经完成交易

        if($shopid['pay_ok']==1){
            $zt=4;
            $zt2='订单已经支付过了';

        }else{

            if($type == 'wechat'){
                try {
                    $weixin = new WeixinPay();
                    $payinfo = $weixin->getPrePayOrder('订单支付', $shopid['danhao'], $shopid['xiaofei']);
                    $redirect_url = urlencode(url('index/index', [],'html', true));
                    header("location:".$payinfo['mweb_url'].'&redirect_url='.$redirect_url);;
                    die();
                }catch (\Exception $e){
                    $zt=2;
                    $zt2=$e->getMessage();
                }
            }elseif($type == 'zfb'){
                try {
                    $ali = Zfb::aliResponse('订单支付', $shopid['danhao'], $shopid['xiaofei'], config('app.alipay.notify_url'));
                    echo $ali;
                    exit();
                }catch (\Exception $e){
                    $zt=2;
                    $zt2=$e->getMessage();
                }
            }else{
                //获取产品信息
                $cp=db('shop')->where('id='.$shopid['shop_id'])->find();
                $jine=$cp['jiage']*$num;
                //  jifen($type,$userid,$num，$source,$jiajian)
                //  type          1为积分    2为金钱    3 为本金  4 为其他
                //  num           数值
                //  $jiajian     1 为 加       2为减
                //  $source       1商城消费  2 会员提现  3会员转账  4 管理变动  5 手动充值  6 微信充值
                //  返回结果     1、执行成功   2 余额不足
                $jianjia=jifen($type,$userid,$jine,1,2,'');

                if($jianjia==1){
                    //修改订单状态
                    $info['pay_ok']=1;
                    $info['is_ok']=2;
                    $info['pay_type']=$type;
                    $info['pay_time']=time();
                    $info['pay_money']=$jine;
                    db('shop_dingdan')->where('id='.$id)->update($info);
                    //减少库存
                    db('shop')->where('id='.$shopid['shop_id'])->setDec('kucun',$num);
                    //删除购物车

                    db('shop_car')->where('shop_id='.$shopid['shop_id'])->where('userid='.$userid)->delete();
                    $zt=1;
                    $zt2='恭喜！支付已经成功';
                    if($cp['catid']==6){
                        $pv=$cp['pv'];
                        $sum=$pv*$num;
                        jihuo($userid,$sum);
                        daili($userid,$shopid['shop_id']);
                    }
                }
                if($jianjia==2){
                    $zt=2;
                    $zt2='抱歉，余额不足';
                }
            }
        }
        $this->assign('zhuangtai2',$zt2);
        $this->assign('zhuangtai',$zt);
        return view();
    }
    //确认收货
    public function qurenshouhuo(){
        $id=input('id');
        $ok=db('shop_dingdan')->where('id',$id)->setField('is_ok',4);
        if($ok==true){
            return array('success'=>1,'msg'=>'确认收货成功');
        }else{
            return array('success'=>0,'msg'=>'确认收货失败');
        }

    }
    //评论
    public function pinglun(){
        $id=input('id');
        if(Request::isAjax()){
            $data=input('post.');
            if(empty($data['content'])){
                return array('code'=>0,'msg'=>'请输入评价内容');
            }
            $data['time']=time();
            $data['shopid']=$data['id'];
            $data['uid']=$this->uid;
            unset($data['id']);
            unset($data['file']);
            db('evaluation')->insert($data);
            db('shop_dingdan')->where('id',$id)->setField('id',4);
            return array('code'=>1,'msg'=>'评价成功');
        }
        $this->assign('id',$id);
        return view();
    }

    public function getPayInfo()
    {
        header('content-type:application/json');
        $order_id = input('order_id');
        $type = input('pay_type');
        $shopid=db('shop_dingdan')->where('id='.$order_id)->find();

        //判断是否已经完成交易

        if($shopid['pay_ok']==1){
            echo json_encode([
                'code'=>0,
                'msg'=>'支付成功'
            ]);
            exit();
        }
        if($type == 'wechat'){
            try {
                $weixin = new WeixinPay();
                $payinfo = $weixin->getPrePayOrder('订单支付', $shopid['danhao'], $shopid['xiaofei']);
                $redirect_url = urlencode(url('index/index', [],'html', true));
                echo json_encode([
                    'code'=>1,
                    'msg'=>'请求成功',
                    'url'=>$payinfo['mweb_url'].'&redirect_url='.$redirect_url
                ]);
//                header("location:".$payinfo['mweb_url'].'&redirect_url='.$redirect_url);;
            }catch (\Exception $e){
                echo json_encode([
                    'code'=>-1,
                    'msg'=>$e->getMessage(),
                ]);
            }
        }elseif($type == 'zfb'){
            try {
                $ali = Zfb::aliResponse('订单支付', $shopid['danhao'], $shopid['xiaofei'], config('app.alipay.notify_url'));
                echo json_encode([
                    'code'=>1,
                    'msg'=>'请求成功',
                    'url'=>$ali
                ]);
            }catch (\Exception $e){
                echo json_encode([
                    'code'=>-1,
                    'msg'=>$e->getMessage(),
                ]);
            }
        }else{
            echo json_encode([
                'code'=>-1,
                'msg'=>'支付方式错误',
            ]);
        }
        exit();
    }

    public function checkOrderStatus()
    {
        header('content-type:application/json');
        $order_id = input('order_id');
        $shopid=db('shop_dingdan')->where('id='.$order_id)->find();
        //判断是否已经完成交易
        if($shopid['pay_ok']==1){
            echo json_encode([
                'code'=>0,
                'msg'=>'支付成功'
            ]);
            exit();
        }else{
            echo json_encode([
                'code'=>1,
                'msg'=>'支付失败'
            ]);
            exit();
        }
        
    }


}